package com.screen.screendisplay.service.impl.ne;

import com.screen.screendisplay.entity.ne.NeProdoperWestPrice;
import com.screen.screendisplay.mapper.ne.NeProdoperWestPriceMapper;
import com.screen.screendisplay.service.ne.NeProdoperWestPriceService;
import com.screen.screendisplay.vo.ne.NeWestElectricPriceVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 蒙西实时电价表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class NeProdoperWestPriceServiceImpl extends ServiceImpl<NeProdoperWestPriceMapper, NeProdoperWestPrice> implements NeProdoperWestPriceService {

    @Autowired
    private NeProdoperWestPriceMapper neProdoperWestPriceMapper;

    @Override
    public List<NeWestElectricPriceVO> getWestElectricPrice(Integer year) {
        List<NeProdoperWestPrice> dataList = neProdoperWestPriceMapper.selectDailyPriceData(30);
        
        // 按日期分组，每组包含三种价格类型数据
        Map<String, List<NeProdoperWestPrice>> groupedData = dataList.stream()
                .collect(Collectors.groupingBy(data -> data.getYear() + "-" + data.getMonth() + "-" + data.getDay()));
        
        List<NeWestElectricPriceVO> resultList = new ArrayList<>();
        
        // 遍历分组数据，构建VO对象
        groupedData.entrySet().stream()
                .sorted((e1, e2) -> e2.getKey().compareTo(e1.getKey())) // 按时间倒序
                .limit(10) // 只取最近10天
                .forEach(entry -> {
                    List<NeProdoperWestPrice> dayData = entry.getValue();
                    
                    NeWestElectricPriceVO vo = new NeWestElectricPriceVO();
                    
                    // 设置年、月、日、日期（从第一条记录获取）
                    if (!dayData.isEmpty()) {
                        NeProdoperWestPrice firstData = dayData.get(0);
                        vo.setYear(firstData.getYear());
                        vo.setMonth(firstData.getMonth());
                        vo.setDay(firstData.getDay());
                        vo.setDate(firstData.getDate());
                    }
                    
                    // 分别设置常规补贴价、平价、其他价格
                    for (NeProdoperWestPrice data : dayData) {
                        if (data.getPriceType() == 0) { // 常规补贴价
                            vo.setSubsidyPrice(data.getPrice());
                        } else if (data.getPriceType() == 1) { // 平价
                            vo.setFlatPrice(data.getPrice());
                        } else if (data.getPriceType() == 2) { // 其他价格
                            vo.setOtherPrice(data.getPrice());
                        }
                    }
                    
                    resultList.add(vo);
                });
        
        return resultList;
    }
}
